const app = getApp();
const { request } = require('../../../utils/request');
const api = require('../../../utils/api.js');
const codeApi = require('../../../utils/codeApi.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    agentDetail: null,
    salesRecords: [],
    id: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({ 
        id: options.id
      });
      
      // 检查代理权限
      this.checkAgentPermission();
    } else {
      wx.showToast({
        title: '缺少代理ID参数',
        icon: 'none',
        complete: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    }
  },

  /**
   * 检查代理权限
   */
  checkAgentPermission() {
    const userId = wx.getStorageSync('userId');
    
    if (!userId) {
      wx.showModal({
        title: '提示',
        content: '未登录或登录已过期，请先登录',
        showCancel: false,
        success: () => {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }
      });
      return;
    }
    
    codeApi.checkPermission(userId)
      .then(res => {
        if (res.code === 0 && res.data && res.data.has_permission) {
          // 获取代理详情
          this.fetchAgentDetail();
          
          // 获取销售记录
          this.fetchSalesRecords();
        } else {
          wx.showModal({
            title: '提示',
            content: '您暂无代理管理权限',
            showCancel: false,
            success: () => {
              wx.navigateBack();
            }
          });
        }
      })
      .catch(err => {
        console.error('检查权限失败', err);
        
        wx.showToast({
          title: '网络错误',
          icon: 'none',
          success: () => {
            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          }
        });
      });
  },

  /**
   * 获取代理详情
   */
  fetchAgentDetail() {
    const { id } = this.data;
    
    if (!id) {
      this.setData({ loading: false });
      return;
    }
    
    const params = {
      agent_id: id
    };
    
    this.setData({ loading: true });
    
    request(api.agent_detail, 'GET', params)
      .then(res => {
        if (res.code === 0 && res.data) {
          this.setData({
            agentDetail: res.data,
            loading: false
          });
        } else {
          this.setData({ loading: false });
          wx.showToast({
            title: res.message || '获取代理详情失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取代理详情失败', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      });
  },

  /**
   * 获取销售记录
   */
  fetchSalesRecords() {
    const { id } = this.data;
    
    if (!id) return;
    
    const params = {
      agent_id: id,
      limit: 10
    };
    
    request(api.agent_sales_records, 'GET', params)
      .then(res => {
        if (res.code === 0 && res.data) {
          this.setData({
            salesRecords: res.data.records || []
          });
        }
      })
      .catch(err => {
        console.error('获取销售记录失败', err);
      });
  },

  /**
   * 修改分成比例
   */
  modifyCommissionRate() {
    const { agentDetail } = this.data;
    
    if (!agentDetail) return;
    
    wx.showModal({
      title: '修改分成比例',
      placeholderText: `当前比例：${agentDetail.commission_rate}%`,
      editable: true,
      content: `${agentDetail.commission_rate}`,
      success: res => {
        if (res.confirm) {
          const newRate = parseFloat(res.content);
          
          if (isNaN(newRate) || newRate < 0 || newRate > 100) {
            wx.showToast({
              title: '请输入有效的分成比例(0-100)',
              icon: 'none'
            });
            return;
          }
          
          this.updateCommissionRate(newRate);
        }
      }
    });
  },

  /**
   * 更新分成比例
   */
  updateCommissionRate(rate) {
    const { id } = this.data;
    
    if (!id) return;
    
    const params = {
      agent_id: id,
      commission_rate: rate
    };
    
    wx.showLoading({
      title: '更新中...',
      mask: true
    });
    
    request(api.update_agent_commission, 'POST', params)
      .then(res => {
        wx.hideLoading();
        
        if (res.code === 0) {
          wx.showToast({
            title: '分成比例更新成功',
            icon: 'success'
          });
          
          // 刷新代理信息
          this.fetchAgentDetail();
        } else {
          wx.showToast({
            title: res.message || '更新失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('更新分成比例失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      });
  },

  /**
   * 发送消息
   */
  sendMessage() {
    const { id, agentDetail } = this.data;
    
    if (!id || !agentDetail) return;
    
    wx.showModal({
      title: '发送消息',
      placeholderText: '请输入消息内容',
      editable: true,
      success: res => {
        if (res.confirm && res.content.trim()) {
          const params = {
            agent_id: id,
            message: res.content.trim()
          };
          
          wx.showLoading({
            title: '发送中...',
            mask: true
          });
          
          request(api.send_agent_message, 'POST', params)
            .then(res => {
              wx.hideLoading();
              
              if (res.code === 0) {
                wx.showToast({
                  title: '消息发送成功',
                  icon: 'success'
                });
              } else {
                wx.showToast({
                  title: res.message || '发送失败',
                  icon: 'none'
                });
              }
            })
            .catch(err => {
              console.error('发送消息失败', err);
              wx.hideLoading();
              wx.showToast({
                title: '网络错误',
                icon: 'none'
              });
            });
        }
      }
    });
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 如果已经有代理ID，刷新代理详情
    if (this.data.id) {
      this.fetchAgentDetail();
      this.fetchSalesRecords();
    }
  }
}) 